<?php

class giftModel extends BpfModel
{

  public function createGift($from)
  {
    return Gift::create($from);
  }

  public function getGift($giftid, $type = 'gifts.gift_id')
  {
    if (empty($giftid)) { return false; }
    static $list = [];
    $cacheid = $giftid . $type;
    if (empty($list[$cacheid])) {
      $mysqlModel = $this->getModel('mysql');
      $gift = $mysqlModel->getSqlBuilder()
        ->from('gifts')
        ->where($type, $giftid)
        ->query()->row('Gift');
      $list[$cacheid] = $gift;
    }
    return $list[$cacheid];
  }

  private function _setGiftsFilter($query, $filter)
  {
    $query->from('gifts')
      ->join('users', 'users.user_id = gifts.user_id');
    if (isset($filter)) {
      if (!empty($filter['search'])) {
        $search = '%' . $filter['search'] . '%';
        $query->WhereGroupStart();
        $query->Where('users.username LIKE', $search);
        $query->orWhere('gifts.name LIKE', $search);
        $query->whereGroupEnd();
      }
      if (isset($filter['status']) && is_numeric($filter['status'])) {
        $query->Where('gifts.status', $filter['status']);
      }
      if (isset($filter['type']) && is_numeric($filter['type'])) {
        $query->Where('gifts.type', $filter['type']);
      }
    }
  }

  public function getGiftsCount($filter = null)
  {
    $mysqlModel = $this->getModel('mysql');
    $query = $mysqlModel->getSqlBuilder()
      ->select('COUNT(0)');
    $this->_setGiftsFilter($query, $filter);
    return $query->query()->field();
  }

  public function getGiftsList($filter = null, $page = 1, $rows = 10)
  {
    $mysqlModel = $this->getModel('mysql');
    $query = $mysqlModel->getSqlBuilder()
        ->select('gifts.*, users.username')
        ->limitPage($rows, $page);
    $this->_setGiftsFilter($query, $filter);
    if (isset($filter['created ASC']) ) {
      $query->orderby('gifts.created asc');
    } else {
      $query->orderby('gifts.created desc');
    }
    return $query->query()->all('Gift');
  }


  public function getPlayerGift($playerGiftid, $type = 'players_gifts._id')
  {
    static $list = [];
    $cacheid = $playerGiftid . $type;
    if (empty($list[$cacheid])) {
      $mysqlModel = $this->getModel('mysql');
      $playerGift = $mysqlModel->getSqlBuilder()
        ->from('players_gifts')
        ->where($type, $playerGiftid)
        ->query()->row('PlayerGift');
      $list[$cacheid] = $playerGift;
    }
    return $list[$cacheid];
  }

  private function _setPlayerGiftsFilter($query, $filter)
  {
    $query->from('players_gifts')
      ->join('players', 'players_gifts.player_id = players.player_id')
      ->join('gifts', 'players_gifts.gift_id = gifts.gift_id');
    if (isset($filter)) {
      if (!empty($filter['search'])) {
        $search = '%' . $filter['search'] . '%';
        $query->WhereGroupStart();
        $query->orWhere('players_gifts.data LIKE', $search);
        $query->whereGroupEnd();
      }
      if (isset($filter['status']) && is_numeric($filter['status'])) {
        $query->Where('players_gifts.status', $filter['status']);
      }
      if (isset($filter['type']) && is_numeric($filter['type'])) {
        $query->Where('gifts.type', $filter['type']);
      }
      if (isset($filter['gift_id']) && is_numeric($filter['gift_id'])) {
        $query->Where('players_gifts.gift_id', $filter['gift_id']);
      }
      if (isset($filter['player_id']) && is_numeric($filter['player_id'])) {
        $query->Where('players_gifts.player_id', $filter['player_id']);
      }
    }
  }

  public function getPlayerGiftsCount($filter = null)
  {
    $mysqlModel = $this->getModel('mysql');
    $query = $mysqlModel->getSqlBuilder()
      ->select('COUNT(0)');
    $this->_setPlayerGiftsFilter($query, $filter);
    return $query->query()->field();
  }

  public function getPlayerGiftsList($filter = null, $page = 1, $rows = 10)
  {
    $mysqlModel = $this->getModel('mysql');
    $query = $mysqlModel->getSqlBuilder()
        ->select('players_gifts.*, players.nickname, players.headimgurl')
        ->select('gifts.type, gifts.flowers')
        ->limitPage($rows, $page);
    $this->_setPlayerGiftsFilter($query, $filter);
    if (isset($filter['created ASC']) ) {
      $query->orderby('players_gifts.created asc');
    } else {
      $query->orderby('players_gifts.created desc');
    }
    return $query->query()->all('PlayerGift');
  }

}

class Gift extends BpfObject
{
  const IS_OFFLINE = 0;
  const IS_ONLINE = 1;

  const IS_PRODUCT = 1;
  const IS_COUPON = 2;

  private function __fetch()
  {
    $this->data = json_decode($this->data, true) ?? [];
  }

  public function getId()
  {
    return $this->gift_id;
  }

  public static function create($form)
  {
    $giftid = BpfObject::getModel('mysql')->getSqlBuilder()->insert('gifts', [
      'user_id' => intval($form['user_id'] ?? 0),
      'name' => trim($form['name']),
      'image' => trim($form['image']),
      'type' => intval($form['type']),
      'amount' => intval($form['amount']),
      'flowers' => intval($form['flowers']),
      'data' => json_encode($form['data'] ?? '') ,
      'status' => intval($form['status']),
      'created' => REQUEST_TIME,
      'updated' => REQUEST_TIME
    ])->query()->insertId();
    return BpfObject::getModel('gift')->getGift($giftid);
  }

  public function update()
  {
    return $this->getModel('mysql')->getSqlBuilder()->update('gifts', [
      'status' => intval($this->status),
      'updated' => REQUEST_TIME
    ], ['gift_id' => $this->gift_id])->query()->affectedRows();
  }

  public function delete()
  {
    //检查奖品是否有兑换记录
    if ($this->getModel('gift')->getPlayerGiftsCount(['gift_id' => $this->gift_id])) {
      return false;
    }
    return $this->getModel('mysql')->getSqlBuilder()->delete('gifts', [
      'gift_id' => $this->gift_id
    ])->query()->affectedRows();
  }

  public function createPlayerGift($form)
  {
    $form['gift_id'] = $this->gift_id;
    $data = $form['data'] ?? [];
    if ($this->type == Gift::IS_COUPON) {
      $data['coupon'] = $this->data['coupon'] ?? '';
      $form['status'] = PlayerGift::IS_SEND;
    } else {
      $form['status'] = PlayerGift::IS_CREATE;
    }
    $data['name'] = $this->name;
    $data['image'] = $this->image;
    $form['data'] = $data;
    if (($playerGift = PlayerGift::create($form)) && $this->type == Gift::IS_PRODUCT) {
      $this->getModel('mysql')->query(join(' ', [
        'UPDATE `gifts` SET `amount` = `amount` - 1,',
          '`status` = IF(`amount` <= 0 AND `status` = ' . GIFT::IS_ONLINE . ', ' . GIFT::IS_OFFLINE . ' , `status`)',
        'WHERE `amount` > 0 AND `gift_id` = ' . $this->gift_id,
      ]) );
    }
    return $playerGift;
  }
}

class PlayerGift extends BpfObject
{
  const IS_CREATE = 0;
  const IS_SEND = 1;

  private function __fetch()
  {
    $this->data = json_decode($this->data, true) ?? [];
  }

  public function getId()
  {
    return $this->_id;
  }

  public static function create($form)
  {
    $playerGiftid = BpfObject::getModel('mysql')->getSqlBuilder()->insert('players_gifts', [
      'player_id' => intval($form['player_id'] ?? 0),
      'gift_id' => intval($form['gift_id'] ?? 0),
      'data' => json_encode($form['data'] ?? ''),
      'status' => intval($form['status']),
      'created' => REQUEST_TIME,
      'updated' => REQUEST_TIME
    ])->query()->insertId();
    return BpfObject::getModel('gift')->getPlayerGift($playerGiftid);
  }

  public function update()
  {
    return $this->getModel('mysql')->getSqlBuilder()->update('players_gifts', [
      'status' => intval($this->status),
      'updated' => REQUEST_TIME
    ], ['_id' => $this->_id])->query()->affectedRows();
  }


}
